package com.liang.maogouyuyin.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.liang.maogouyuyin.R
import com.liang.maogouyuyin.bean.PetBean
import com.liang.maogouyuyin.databinding.ItemPetBinding
import com.liang.maogouyuyin.local.LocalRepository
import com.liang.maogouyuyin.utils.DateUtil
import com.liang.maogouyuyin.widget.popup.SelectPetPopup
import com.bumptech.glide.Glide
import java.io.File

class PetAdapter(val context: Context): RecyclerView.Adapter<PetAdapter.ViewHolder>() {
    class ViewHolder(binding: ItemPetBinding): RecyclerView.ViewHolder(binding.root) {
        val itemProfile = binding.itemPetProfilePhoto
        val itemName = binding.itemPetName
        val itemAge = binding.itemPetAge
        val itemAccompany = binding.itemPetAccompany
    }

    interface SelectListener {
        fun select(petName: String)
    }

    private lateinit var list: ArrayList<PetBean>

    private var selectListener: SelectListener? = null

    private lateinit var popup: SelectPetPopup

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemPetBinding.inflate(LayoutInflater.from(context), parent, false)
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val bean = list[position]
        Glide.with(context).load(File(bean.profile)).into(holder.itemProfile)
        holder.itemName.text = bean.name
        holder.itemAge.text = String.format(context.getString(R.string.record_default_format_pet_age), DateUtil.getAge(bean.birthday))
        holder.itemAccompany.text = String.format(context.getString(R.string.record_default_format_pet_accompany), DateUtil.getDays(bean.arriveHome))
        holder.itemView.setOnClickListener {
            LocalRepository.currentPet = bean.name
            selectListener?.select(bean.name)
            popup.dismiss()
        }
    }

    fun setList(list: ArrayList<PetBean>) {
        this.list = list
    }

    fun setSelectListener(listener: SelectListener) {
        this.selectListener = listener
    }

    fun setPopup(popup: SelectPetPopup) {
        this.popup = popup
    }
}